﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;

using CE.User;
using CE.Global;
using CE.Database;
using CE.Report;

public partial class telereport_check_notTHname : System.Web.UI.Page
{
    string PageCode = "GGRPTTRGGENUR";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/ManagementSecureLogin.aspx");
        }

        if (!IsPostBack)
        {
            if (Convert.ToInt64(Session[General.UserId].ToString()) != 1)
            {
                CheckPageAccess();
            }

            lblError.Text = "";
            lblContent.Text = "";
            lblUpdateError.Text = "";
            lblUpdateMessage.Text = "";
            ddlDay1.Visible = true;
            lblFromDate.Text = "Date :";
            lblToDate.Visible = false;
            ddlDay2.Visible = false;
            ddlMonth2.Visible = false;
            ddlYear2.Visible = false;
            ddlYear1.Items.Clear();
            ddlYear2.Items.Clear();

            int _cryr = CE.Global.General.GetUTCDateTime().Year;
            int _styr = 2010;
            for (int _year = _cryr; _year >= _styr; _year--)
            {
                ddlYear1.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
                ddlYear2.Items.Add(new ListItem(_year.ToString(), _year.ToString()));
            }

            ddlDay1.Text = CE.Global.General.GetUTCDateTime().Day.ToString("00");
            ddlMonth1.Text = CE.Global.General.GetUTCDateTime().Month.ToString("00");
            ddlYear1.Text = CE.Global.General.GetUTCDateTime().Year.ToString("0000");
            ddlDay2.Text = CE.Global.General.GetUTCDateTime().Day.ToString("00");
            ddlMonth2.Text = CE.Global.General.GetUTCDateTime().Month.ToString("00");
            ddlYear2.Text = CE.Global.General.GetUTCDateTime().Year.ToString("0000");
            ddlReportType_SelectedIndexChanged(null, null);
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblError.Text = "";
        lblUpdateError.Text = "";
        lblUpdateMessage.Text = "";
        txtReportType.Text = ddlReportType.Text;
        txtAgentId.Text = Session[CE.Global.General.UserId].ToString();
        btnUpdate.Visible = false;
        LoadGrid();
    }

    protected void ddlReportType_SelectedIndexChanged(object sender, EventArgs e)
    {
        lblError.Text = "";
        ddlDay1.Text = CE.Global.General.GetUTCDateTime().Day.ToString("00");
        ddlDay2.Text = CE.Global.General.GetUTCDateTime().Day.ToString("00");
        ddlMonth1.Text = CE.Global.General.GetUTCDateTime().Month.ToString("00");
        ddlMonth2.Text = CE.Global.General.GetUTCDateTime().Month.ToString("00");
        ddlYear1.Text = CE.Global.General.GetUTCDateTime().Year.ToString("0000");
        ddlYear2.Text = CE.Global.General.GetUTCDateTime().Year.ToString("0000");
        if (Convert.ToInt16(ddlReportType.Text) == 0)
        {
            ddlDay1.Visible = false;
            lblFromDate.Text = "Date :";
            lblToDate.Visible = false;
            ddlDay2.Visible = false;
            ddlMonth2.Visible = false;
            ddlYear2.Visible = false;
        }
        else if (Convert.ToInt16(ddlReportType.Text) == 1)
        {
            ddlDay1.Visible = true;
            lblFromDate.Text = "Date :";
            lblToDate.Visible = false;
            ddlDay2.Visible = false;
            ddlMonth2.Visible = false;
            ddlYear2.Visible = false;
        }
        else if (Convert.ToInt16(ddlReportType.Text) == 2)
        {
            lblFromDate.Text = "From Date :";
            lblToDate.Text = " To Date :";
            lblToDate.Visible = true;
            ddlDay2.Visible = true;
            ddlMonth2.Visible = true;
            ddlYear2.Visible = true;
            ddlDay1.Visible = true;
        }
    }

    protected void grvEnglishName_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Int32 IsThai = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "IsThai"));
            Int32 IsReject = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "IsReject"));
            Int32 IsUpdated = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "IsUpdated"));

            txtIsUpdated.Text = IsUpdated.ToString();

            Label lblStatus = new Label();
            RadioButton rdoThai = new RadioButton();
            RadioButton rdoEnglish = new RadioButton();
            RadioButton rdoReject = new RadioButton();
            Button UpdateButton = new Button();
            lblStatus = (Label)e.Row.FindControl("lblStatus");
            rdoThai = (RadioButton)e.Row.FindControl("rdoThai");
            rdoEnglish = (RadioButton)e.Row.FindControl("rdoEnglish");
            rdoReject = (RadioButton)e.Row.FindControl("rdoReject");
            UpdateButton = (Button)e.Row.FindControl("UpdateButton");

            if (IsUpdated == 1)
            {
                e.Row.Cells[0].BackColor = System.Drawing.Color.LightGreen;
                e.Row.Cells[1].BackColor = System.Drawing.Color.LightGreen;
                e.Row.Cells[2].BackColor = System.Drawing.Color.LightGreen;
                e.Row.Cells[6].BackColor = System.Drawing.Color.LightGreen;
                e.Row.Cells[7].BackColor = System.Drawing.Color.LightGreen;
                e.Row.Cells[8].BackColor = System.Drawing.Color.LightGreen;

                lblStatus.Text = "YES";
                lblStatus.ForeColor = System.Drawing.Color.Green;

                rdoThai.Enabled = false;
                rdoEnglish.Enabled = false;
                rdoReject.Enabled = false;

                UpdateButton.Enabled = false;
                if (IsReject == 0)
                {
                    if (IsThai == 1)
                    {
                        rdoThai.Checked = true;
                    }
                    else if (IsThai == 0)
                    {
                        rdoEnglish.Checked = true;
                    }
                    else
                    {
                        rdoReject.Checked = true;
                    }
                }
                else
                {
                    rdoReject.Checked = true;
                }
            }
            else
            {
                lblStatus.Text = "NO";
                lblStatus.ForeColor = System.Drawing.Color.Red;

                rdoThai.Enabled = true;
                rdoEnglish.Enabled = true;
                rdoReject.Enabled = true;

                UpdateButton.Enabled = true;
                rdoThai.Checked = false;
                rdoEnglish.Checked = false;
                rdoReject.Checked = false;
            }

            /*CheckBox chkIsThai = new CheckBox();
            chkIsThai = (CheckBox)e.Row.FindControl("chkThaiName");
            if (IsThai == 0)
            {
                chkIsThai.Checked = false;
            }
            else if (IsThai == 1)
            {
                chkIsThai.Checked = true;
            }*/

        }
    }
    
    protected void grvEnglishName_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("MYUPDATE"))
        {
            if (e.CommandArgument != null)
            {               
                string THUserId = "0";
                string ENUserId = "0";
                string REUserId = "0";
                Int64 ReportUser = 0;
                string RecordDate = txtReportDate1.Text.Trim();
                if (Session[CE.Global.General.UserId] != null)
                {
                    ReportUser = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                }

                GridViewRow gvr = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                int RowIndex = gvr.RowIndex;
                GridViewRow row = grvEnglishName.Rows[RowIndex];
                RadioButton rdoThai = (RadioButton)row.FindControl("rdoThai");
                RadioButton rdoEnglish = (RadioButton)row.FindControl("rdoEnglish");
                RadioButton rdoReject = (RadioButton)row.FindControl("rdoReject");
                Button UpdateButton = (Button)row.FindControl("UpdateButton");
                if (rdoThai.Checked)
                {
                    THUserId = e.CommandArgument.ToString();
                }
                else if (rdoEnglish.Checked)
                {
                    ENUserId = e.CommandArgument.ToString();
                }
                else if (rdoReject.Checked)
                {
                    REUserId = e.CommandArgument.ToString();
                }

                Int64 _result = 0;
                _result = UpdateENTHNameStatus(THUserId, ENUserId, REUserId, RecordDate, ReportUser);
                if (_result > 0)
                {
                    UpdateButton.Enabled = false;
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Update was successful.');", true);
                }
                else
                {
                    UpdateButton.Enabled = true;
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('Update failed.');", true);
                }

            }
        }
    }

    public bool ValidDate(Int32 Year, Int32 Month, Int32 Day)
    {
        bool _isValid = true;
        int daysInMonth = 0;
        string leap, monthValid, dayValid, yearValid;
        if (Year >= 0000)
        {
            yearValid = "yes";
        }
        else
        {
            yearValid = "no";
        }
        if (Year % 400 == 0)
        {
            leap = "yes";
        }
        else if (Year % 100 == 0)
        {
            leap = "no";
        }
        else if (Year % 4 == 0)
        {
            leap = "yes";
        }
        else
        {
            leap = "no";
        }

        switch (Month)
        {
            case 1: daysInMonth = 31;
                break;
            case 3: daysInMonth = 31;
                break;
            case 4: daysInMonth = 30;
                break;
            case 5: daysInMonth = 31;
                break;
            case 6: daysInMonth = 30;
                break;
            case 7: daysInMonth = 31;
                break;
            case 8: daysInMonth = 31;
                break;
            case 9: daysInMonth = 30;
                break;
            case 10: daysInMonth = 31;
                break;
            case 11: daysInMonth = 30;
                break;
            case 12: daysInMonth = 31;
                break;
        }

        if (Month >= 1 && Month <= 12)
        {
            monthValid = "yes";
        }
        else
        {
            monthValid = "no";
        }
        if (Month == 2)
        {
            if (leap == "no")
            {
                daysInMonth = 28;
            }
            else if (leap == "yes")
            {
                daysInMonth = 29;
            }
        }

        if (1 <= Day && Day <= daysInMonth)
        {
            dayValid = "yes";
        }

        else
        {
            dayValid = "no";
        }

        if ((dayValid == "yes") && (monthValid == "yes") && (yearValid == "yes"))
        {
            _isValid = true;
        }
        else
        {
            _isValid = false;
        }

        return _isValid;
    }

    public string GetMonth(string month)
    {
        string result = "";
        if (month == "01")
        {
            result = " Jan ";
        }
        else if (month == "02")
        {
            result = " Feb ";
        }
        else if (month == "03")
        {
            result = " Mar ";
        }
        else if (month == "04")
        {
            result = " Apr ";
        }
        else if (month == "05")
        {
            result = " May ";
        }
        else if (month == "06")
        {
            result = " Jun ";
        }
        else if (month == "07")
        {
            result = " Jul ";
        }
        else if (month == "08")
        {
            result = " Aug ";
        }
        else if (month == "09")
        {
            result = " Sep ";
        }
        else if (month == "10")
        {
            result = " Oct ";
        }
        else if (month == "11")
        {
            result = " Nov ";
        }
        else if (month == "12")
        {
            result = " Dec ";
        }
        return result;
    }

    public bool Validatioin()
    {
        lblError.Text = "";
        bool _isValid = true;
        DateTime _fromDate, _toDate;
        if (Convert.ToInt16(ddlReportType.Text) == 1)
        {
            if (ddlDay1.SelectedIndex >= 0)
            {
                if (ValidDate(Convert.ToInt32(ddlYear1.Text), Convert.ToInt32(ddlMonth1.Text), Convert.ToInt32(ddlDay1.Text)))
                {
                    _fromDate = Convert.ToDateTime(Convert.ToInt32(ddlYear1.Text) + "/" + Convert.ToInt32(ddlMonth1.Text) + "/" + Convert.ToInt32(ddlDay1.Text));
                    if (_fromDate > CE.Global.General.GetUTCDateTime())
                    {
                        _isValid = false;
                        lblError.Text = "Date should be less than or equal to Today";
                    }
                }
                else
                {
                    _isValid = false;
                    lblError.Text = "Select Valid Date";
                }
            }
            else
            {
                _isValid = false;
                lblError.Text = "Select Date";
            }
        }
        else if (Convert.ToInt16(ddlReportType.Text) == 2)
        {
            if (ddlDay1.SelectedIndex >= 0 && ddlDay2.SelectedIndex >= 0)
            {
                if (ValidDate(Convert.ToInt32(ddlYear1.Text), Convert.ToInt32(ddlMonth1.Text), Convert.ToInt32(ddlDay1.Text)))
                {
                    _fromDate = Convert.ToDateTime(Convert.ToInt32(ddlYear1.Text) + "/" + Convert.ToInt32(ddlMonth1.Text) + "/" + Convert.ToInt32(ddlDay1.Text));
                    if (ValidDate(Convert.ToInt32(ddlYear2.Text), Convert.ToInt32(ddlMonth2.Text), Convert.ToInt32(ddlDay2.Text)))
                    {
                        _toDate = Convert.ToDateTime(Convert.ToInt32(ddlYear2.Text) + "/" + Convert.ToInt32(ddlMonth2.Text) + "/" + Convert.ToInt32(ddlDay2.Text));
                        if (_fromDate <= CE.Global.General.GetUTCDateTime())
                        {
                            if (_fromDate > _toDate)
                            {
                                _isValid = false;
                                lblError.Text = "From date should be less than To date";
                            }
                        }
                        else
                        {
                            _isValid = false;
                            lblError.Text = "From date should be less than Today";
                        }
                    }
                    else
                    {
                        _isValid = false;
                        lblError.Text = "Select Valid To date";
                    }
                }
                else
                {
                    _isValid = false;
                    lblError.Text = "Select Valid From date";
                }
            }
            else
            {
                _isValid = false;
                lblError.Text = "Select From date and To date";
            }
        }
        return _isValid;
    }

    public void LoadGrid()
    {
        lblError.Text = "";
        lblRecordCount.Text = "";
        lblUpdateError.Text = "";
        lblUpdateMessage.Text = "";
        if (Validatioin() == true)
        {
            txtReportDate1.Text = "";
            txtReportDate2.Text = CE.Global.General.GetUTCDateTime().Year.ToString("0000") + CE.Global.General.GetUTCDateTime().Month.ToString("00") + CE.Global.General.GetUTCDateTime().Day.ToString("00");
            txtReportDate1.Text = ddlYear1.Text;
            txtReportDate1.Text += ddlMonth1.Text;
            if (ddlReportType.SelectedIndex > 0 || ddlReportType.Text == "1")
            {
                if (ddlDay1.SelectedIndex >= 0)
                {
                    txtReportDate1.Text += ddlDay1.Text;
                }
            }
            if (ddlReportType.SelectedIndex == 2)
            {
                txtReportDate2.Text = ddlYear2.Text;
                txtReportDate2.Text += ddlMonth2.Text;
                txtReportDate2.Text += ddlDay2.Text;
            }
            DataTable _dtSummary = new DataTable();
            Int16 _ReportType = Convert.ToInt16(ddlReportType.Text);
            string _ReportDate = txtReportDate1.Text.Trim();


            MyDatabase _db = new MyDatabase("GGR_DBConnectionString");
            string _spName = "[sprocReportsGGEnglishNameSelectedList]";
            SortedList _sPara = new SortedList();

            _sPara.Add("@ReportType", _ReportType);
            _sPara.Add("@ReportDate", _ReportDate);

            _dtSummary = _db.GetDataTableBySP(_spName, _sPara);
            if (_dtSummary != null && _dtSummary.Rows.Count > 0)
            {
                lblError.Text = "";
                btnUpdate.Visible = true;
                //btnUpdate.Enabled = true;
                grvEnglishName.DataSource = _dtSummary;
                grvEnglishName.DataBind();
                lblRecordCount.Text = "(" + grvEnglishName.Rows.Count.ToString() + ") record(s).";
            }
            else
            {
                btnUpdate.Visible = false;
                //btnUpdate.Enabled = false;
                grvEnglishName.DataSource = null;
                grvEnglishName.DataBind();
            }
        }
        else
        {
            btnUpdate.Visible = false;
            //btnUpdate.Enabled = false;
            grvEnglishName.DataSource = null;
            grvEnglishName.DataBind();
        }
        CheckPageAccess();
    }

    public void ExportGridView(string fileName, Label lblContent)
    {
        string attachment = "attachment; filename=" + fileName + ".xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        Response.Write(lblContent.Text);
        Response.End();
    }

    private void CheckPageAccess()
    {
        Int64 PageAccess = General.GetPageAccess(Convert.ToInt64(Session[General.UserId].ToString()), PageCode);
        if (PageAccess == 0)
        {
            Response.Redirect("~/UserMessage.aspx?menu=0&mt=UM&ec=101");
        }
        else
        {
            //EnablePageAccess(PageAccess);
        }
    }

    private void EnablePageAccess(Int64 PageAccess)
    {
        if (PageAccess == 100)
        {
            //btnUpdate.Enabled = false;
        }
        else if (PageAccess == 200)
        {
            //btnUpdate.Enabled = true;
            if (txtIsUpdated.Text != "0")
            {
                //btnUpdate.Enabled = false;
            }
        }
    }

    private Int64 UpdateENTHNameStatus(string THUserId, string ENUserId, string REUserId, string RecordDate, Int64 ReportUser)
    {
        MyDatabase _db = new MyDatabase("GGR_DBConnectionString");
        Int64 _result = -1;
        string _spName = "sprocCXCRMEnglishNameCustomerStatusUpdateSelectedList";

        SortedList _sPara = new SortedList();
        _sPara.Add("@THUserId", THUserId);
        _sPara.Add("@ENUserId", ENUserId);
        _sPara.Add("@REUserId", REUserId);
        _sPara.Add("@RecordDate", RecordDate);
        _sPara.Add("@ReportUser", ReportUser);
        _result = _db.ExecuteSP(_spName, _sPara);

        return _result;
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        lblError.Text = "";
        lblUpdateError.Text = "";
        lblUpdateMessage.Text = "";
        Int32 _IsSuccess = 0;
        Int32 _IsFaild = 0;
        Int32 _Total = 0;
        if (grvEnglishName.Rows.Count > 0)
        {
            for (int i = 0; i < grvEnglishName.Rows.Count; i++)
            {
                string THUserId = "0";
                string ENUserId = "0";
                string REUserId = "0";
                Int64 ReportUser = 0;
                string RecordDate = txtReportDate1.Text.Trim();
                if (Session[CE.Global.General.UserId] != null)
                {
                    ReportUser = Convert.ToInt64(Session[CE.Global.General.UserId].ToString());
                }

                GridViewRow row = grvEnglishName.Rows[i];
                string Status = ((Label)row.FindControl("lblStatus")).Text;
                bool isTHChecked = ((CheckBox)row.FindControl("rdoThai")).Checked;
                bool isENChecked = ((CheckBox)row.FindControl("rdoEnglish")).Checked;
                bool isREChecked = ((CheckBox)row.FindControl("rdoReject")).Checked;
                if (Status == "NO")
                {
                    if (isTHChecked)
                    {
                        THUserId = grvEnglishName.Rows[i].Cells[0].Text;
                    }
                    else if (isENChecked)
                    {
                        ENUserId = grvEnglishName.Rows[i].Cells[0].Text;
                    }
                    else if (isREChecked)
                    {
                        REUserId = grvEnglishName.Rows[i].Cells[0].Text;
                    }
                    if (isTHChecked == true || isENChecked == true || isREChecked == true)
                    {
                        _Total += 1;
                        Int64 _result = 0;
                        _result = UpdateENTHNameStatus(THUserId, ENUserId, REUserId, RecordDate, ReportUser);
                        if (_result > 0)
                        {
                            _IsSuccess += 1;
                        }
                        else
                        {
                            _IsFaild += 1;
                        }
                    }
                }
            }
            if (_Total == _IsSuccess)
            {
                string Success =  "Update was Successful";
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Success.ToString() + "');", true);
            }
            else if (_IsFaild > 0)
            {
                string Error = _IsFaild.ToString() + "Record(s) Updated Failed";
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Error.ToString() + "');", true);
            }
            LoadGrid();
        }

    }

}